package com.cloud.drore.eboss.sso.controller;

import com.cloud.drore.eboss.sso.base.Constants;
import com.cloud.drore.eboss.sso.base.ResultMessage;
import com.cloud.drore.eboss.sso.entity.Function;
import com.cloud.drore.eboss.sso.entity.ShiroUser;
import com.cloud.drore.eboss.sso.po.PasswordReset;
import com.cloud.drore.eboss.sso.po.UserAndFunction;
import com.cloud.drore.eboss.sso.service.FunctionService;
import com.cloud.drore.eboss.sso.service.RoleRightService;
import com.cloud.drore.eboss.sso.service.ShiroRoleService;
import com.cloud.drore.eboss.sso.service.ShiroUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 浙江卓锐科技股份有限公司 版权所有 © Copyright 2018<br>
 *
 * @Description: <br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/3/15 9:35 <br>
 * @Author: <a href="836327318@qq.com">吴昌益</a>
 */
@Slf4j
@RestController
@Api(value = "/用户接口", description = "用户接口-wcy")
public class UserController {

    @Autowired
    ShiroUserService shiroUserService;

    @Autowired
    ShiroRoleService shiroRoleService;

    @Resource
    RedisTemplate redisTemplate;

    @Value("${shiro.session.global-session-timeout}")
    private Long global_session_timeout;

    @Value("${shiro.dealer}")
    private String dealerUrl;

    @Value("${shiro.supplier}")
    private String supplierUrl;

    @Value("${shiro.operation}")
    private String operationUrl;

    private static int COOKIE_MAX_AGE = 1200;

    @Autowired
    FunctionService functionService;

    @Autowired
    RoleRightService roleRightService;

    @ResponseBody
    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultMessage<ShiroUser> login(@RequestBody ShiroUser user) {

        String username = user.getUsername();
        String password = new Md5Hash(user.getPassword(), "www", 1024).toBase64();

        ShiroUser shiroUser = shiroUserService.findByUsername(username);


        if(shiroUser==null)
            return ResultMessage.error(8300, "用户名密码错误");

        shiroUser = shiroUserService.findByUsernameAndPassword(username, password);

        if(shiroUser!=null){
            return ResultMessage.success(shiroUser);
        }else
            return ResultMessage.error(8300, "用户名密码错误");
    }

    @ResponseBody
    @ApiOperation(value = "查询用户")
    @RequestMapping(value = "/admin/getUserByUserName", method = RequestMethod.POST)
    public ShiroUser getUser(@RequestBody ShiroUser shiroUser) {
        return shiroUserService.findByUsername(shiroUser.getUsername());
    }

    @ResponseBody
    @ApiOperation(value = "查询用户")
    @RequestMapping(value = "/admin/user/{id}", method = RequestMethod.GET)
    public ShiroUser getUser(@PathVariable("id") Long id) {
        return shiroUserService.get(id);
    }

    @ResponseBody
    @ApiOperation(value = "获取商户的管理员")
    @RequestMapping(value = "/admin/adminuser/{typeid}", method = RequestMethod.GET)
    public ShiroUser getUserByMetaId(@PathVariable("typeid") Long typeid) {
        return shiroUserService.getUserByTypeId(typeid);
    }

    @ResponseBody
    @ApiOperation(value = "通过用户id获取用户信息和权限信息")
    @RequestMapping(value = "admin/user_function/{id}", method = RequestMethod.GET)
    UserAndFunction findUserFunctionById(@PathVariable("id") Long id){
        return shiroUserService.getUserFunction(id);
    }

   /**
    * @ClassName: UserController
    * @param
    * @Return: 
    * @Decription: 
    * @CreateDate: Created in 2018/3/27 10:12
    * @Author: <a href="836327318@qq.com">吴昌益</a>
    * @Modify: 
    */
    @RequestMapping(value = "/admin/user/password", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改密碼")
    public ResultMessage password(@RequestBody PasswordReset passwordReset) {

        String oldpassword = passwordReset.getOldpassword();

        String username = passwordReset.getUsername();

        String password = passwordReset.getPassword();

        ShiroUser user = shiroUserService.findByUsername(username);

        oldpassword = new Md5Hash(oldpassword, "www",1024).toBase64();


        if (!oldpassword.equals(user.getPassword())) {
            return ResultMessage.error(8300,"旧密码错误");
        } else {
            user.setPassword(new Md5Hash(password, "www", 1024).toBase64());
            shiroUserService.save(user);
        }

        return ResultMessage.success("修改密码成功");
    }

    /**
     * @ClassName: UserController
     * @param shiroUser
     * @Return: java.lang.String
     * @Decription: 校验用户名或者邮箱是否存在
     * @CreateDate: Created in 2018/3/15 9:54
     * @Author: <a href="836327318@qq.com">吴昌益</a>
     * @Modify:
     */
    @RequestMapping(value = "/checkNameOrEmallExist", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "校验用户名或者邮箱是否存在")
    public ResultMessage checkNameOrEmallExist(@RequestBody ShiroUser shiroUser) {

        Boolean responseJson = shiroUserService.checkNameOrEmallExist(shiroUser);
        if(responseJson){
            return ResultMessage.success(true);
        }else{
            return ResultMessage.success(false);
        }

    }

    @RequestMapping(value = "/admin/editUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑用户")
    public ResultMessage editUser(@RequestBody ShiroUser shiroUser) {
        shiroUserService.editUser(shiroUser);

        return ResultMessage.success("修改成功");
    }

    @RequestMapping(value = "/admin/addUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加用户用户")
    public ResultMessage addUser(@RequestBody @Valid ShiroUser shiroUser) {

        Boolean responseJson = shiroUserService.checkNameOrEmallExist(shiroUser);

        if(!responseJson)
            return ResultMessage.error(8300, "用户名或邮箱已经存在！！");

        ResultMessage resultMessage = shiroUserService.addUser(shiroUser);

        return resultMessage;
    }

    @RequestMapping(value = "/admin/addUserAndRight", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加用户和权限")
    public ResultMessage addUserAndRight(@RequestBody UserAndFunction userAndFunction) {

        Boolean responseJson = shiroUserService.checkNameOrEmallExist(userAndFunction.getShiroUser());

        if(!responseJson)
            return ResultMessage.error(8300, "用户名或邮箱已经存在！！");

        ResultMessage resultMessage = shiroUserService.addUserAndFunction(userAndFunction.getShiroUser(),userAndFunction.getEbossRoleRightRelation());
        resultMessage.setMessage("添加成功");
        return resultMessage;
    }

    @RequestMapping(value = "/admin/updateUserAndRight", method = RequestMethod.PUT)
    @ResponseBody
    @ApiOperation(value = "修改用户和权限")
    public ResultMessage updateUserAndRight(@RequestBody @Valid UserAndFunction userAndFunction) {

        roleRightService.deleteByuserId(userAndFunction.getShiroUser().getId());

        ResultMessage resultMessage = shiroUserService.addUserAndFunction(userAndFunction.getShiroUser(),userAndFunction.getEbossRoleRightRelation());
        resultMessage.setMessage("修改成功");
        return resultMessage;
    }

    /**
     *
     * 功能列表
     *
     * @return
     */
    @ApiOperation(value = "功能权限列表")
        @RequestMapping(value = "/admin/function_list/{project}", method = RequestMethod.GET)
    @ResponseBody
    ResultMessage findFunctionManagerList(@PathVariable("project") String projectname) {

        List<Function> pageResonse = functionService.findAllByPage(projectname);

        return ResultMessage.success(pageResonse);
    }

    /**
     *
     * 功能列表
     *
     * @return
     */
    @ApiOperation(value = "获取用户列表")
    @RequestMapping(value = "/admin/user_list/{type}/{typeId}", method = RequestMethod.GET)
    @ResponseBody
    ResultMessage findUserList(@PathVariable("type") String type, @PathVariable("typeId") Long typeId) {

        List<ShiroUser> resonse = shiroUserService.findList(type, typeId);

        return ResultMessage.success(resonse);
    }

    /**
     *
     * 功能列表
     *
     * @return
     */
    @ApiOperation(value = "重置密码")
    @RequestMapping(value = "/admin/resetPassword/{id}", method = RequestMethod.GET)
    @ResponseBody
    ResultMessage resetPassword(@PathVariable("id") Long id) {

        shiroUserService.resetPassword(id);
        return ResultMessage.success(Constants.initPassword);
    }

    /**
     *
     * 功能列表
     *
     * @return
     */
    @ApiOperation(value = "用户作废")
    @RequestMapping(value = "/admin/disableUser/{id}/{status}", method = RequestMethod.GET)
    @ResponseBody
    ResultMessage disableUser(@PathVariable("id") Long id, @PathVariable("status") int status) {

        if(status == Constants.userStatus_2){
            shiroUserService.disableUser(id, status);
        }else if(status == Constants.userStatus_1)
            shiroUserService.disableUser(id, status);
        else
            return ResultMessage.error(8500, "操作失敗！！");
        return ResultMessage.success("操作成功！！");
    }

}
